/*
 * @Author: mat
 * @Date: 2020-10-14 23:09:46
 * @LastEditTime: 2020-12-21 01:03:53
 * @Description: websocket 封装
 * @使用示例:
let socketConfig = {
	url: '/ints/websocket/test',
	callback: this.getSocketMsg,
	msg: {
		fanId: '01'
	}
}
let testSocket = new SocketPlugin(socketConfig)
// 初始化
testSocket.connect()
// 发送消息
testSocket.send(socketConfig.msg)
// 关闭
testSocket.close()
*/

class SocketPlugin {
	constructor(param) {
		this.websocket = null;
		this.isConnect = false;
		this.timeoutNum = null;
		this.isActivelyClose = false;
		this.param = param;
	}
	connect() {
		this.websocket = new WebSocket(this.param.url);
		this.initSocket(this.param);
	}
	initSocket(param) {
		this.isActivelyClose = false;

		this.websocket.onclose = (e) => {
			this.isConnect = false;
			// 如果手动关闭则不进行重连
			if (!this.isActivelyClose) {
				this.reconnectSocket(param);
			}
		};
		this.websocket.onerror = (e) => {
			this.reconnectSocket(param);
		};
		this.websocket.onopen = () => {
			this.isConnect = true;
			if (param.hasOwnProperty('msg')) {
				this.send(param.msg || '');
			}
		};
		this.websocket.onmessage = (e) => {
			param.callback(JSON.parse(e.data));
		};
	}
	reconnectSocket(param) {
		if (this.isConnect === true) {
			return false;
		}
		this.isConnect = true;
		this.timeoutNum && clearTimeout(this.timeoutNum);
		this.timeoutNum = setTimeout(() => {
			this.connect(param);
			this.isConnect = false;
		}, 1000);
	}
	/**
	 * // websocket连接状态下才能进行send
	 * @param {*} msg
	 * 向服务send的消息
	 */
	send(msg) {
		this.websocket.send(JSON.stringify(msg));
	}
	close() {
		this.isActivelyClose = true;
		if (this.websocket) {
			this.websocket.close();
		}
	}
}

export default SocketPlugin;
